"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/7/16 8:38
@Description : 

"""
from django.core.paginator import Paginator
from django2512 import settings


# 分页工具
def page_util(request, data_list):
    # 一页10条数据    第一页     参数 1  数据列表   参数2 每页展示的条数
    paginator = Paginator(data_list, settings.PER_PAGE)
    # 获取数据总条数
    total = paginator.count
    # 总页数
    pages = paginator.num_pages
    # 分页区间
    page_range = paginator.page_range
    # 获取当前页页码
    page_num = int(request.GET.get('page', default=1))
    # 当前页对象
    current_page = paginator.get_page(page_num)
    # 当前页数据列表
    table_data = current_page.object_list
    # 下一页页码
    try:
        next_page = current_page.next_page_number()
    except Exception as e:
        next_page = pages
    # 上一页页码
    try:
        pre_page = current_page.previous_page_number()
    except Exception as e:
        pre_page = 1

    # 判定是否还有上一页
    has_pre_page = current_page.has_previous()
    # 判定是否还有下一页
    has_next_page = current_page.has_next()
    context = {
        'total': total,
        'table_data': table_data,
        'pages': pages,
        'page_range': customer_page_range(pages, page_num),
        'has_pre_page': has_pre_page,
        'has_next_page': has_next_page,
        'pre_page': pre_page,
        'next_page': next_page,
        'page_num': page_num,
    }

    return context


# 分页区间
def customer_page_range(total_pages, current_page, NAV_SIZE=settings.NAV_SIZE):
    # 起始位置
    min = current_page - NAV_SIZE // 2
    min = min if min > 1 else 1
    # 结束位置
    max = min + NAV_SIZE   # (1,11)
    max = max if max < total_pages else total_pages
    page_range = range(min, max+1)
    return page_range

#  (1,11)   (2,12)
if __name__ == '__main__':
    min, max = customer_page_range(20, 1, 10)
    print(min, max)
